package com.micro.utils;

import com.micro.entity.TaskInfo;
import com.micro.global.TaskInfoDataBase;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 序列化，用于保存数据
 *
 * @author dufen
 */
@Slf4j
public class SeriaUtil {
    private static final String FILE_PATH = "db.obj";
    private static final File FILE = new File(FILE_PATH);

    public static synchronized void writeObjectToFile(Object obj, String filePath) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(obj);
            oos.flush();
        } catch (IOException e) {
            log.info("写出序列化数据异常：{}", e);
        }
    }


    public static synchronized <T> T readObjectToFile(String filePath, Class<T> tClass) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            return tClass.cast(ois.readObject());
        } catch (Exception e) {
            log.info("读出序列化对象文件不存在：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static synchronized void readData() {
        try {
            List<TaskInfo> list = SeriaUtil.readObjectToFile(FILE_PATH, List.class);
            list.stream().map(taskInfo -> {
                if (!taskInfo.isComplete()) {
                    taskInfo.setOperation("暂停中...");
                }
                return taskInfo;
            }).forEach(TaskInfoDataBase.DATABASE::add);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static synchronized void writeData() {
        List<TaskInfo> list = new ArrayList<>();
        TaskInfoDataBase.DATABASE.stream().sorted(Comparator.comparing(t -> Integer.valueOf(t.getId()))).map(taskInfo -> {
            taskInfo.setId(TaskInfoDataBase.DATABASE.indexOf(taskInfo) + 1);
            return taskInfo;
        }).forEach(list::add);
        SeriaUtil.writeObjectToFile(list, FILE_PATH);
    }

    public static synchronized void backUpDataBase(){
        List<TaskInfo>list = new ArrayList<>();
        TaskInfoDataBase.DATABASE.stream().forEach(list::add);
        writeObjectToFile(list,"backup.obj");
    }
    public static synchronized void restoreDataBase(){
        List<TaskInfo> list = readObjectToFile("backup.obj", List.class);
        list.stream().forEach(TaskInfoDataBase.DATABASE::add);
    }
}
